package com.haotunet.app.goldtreasure.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.BuyConfirmModel;
import com.haotunet.app.goldtreasure.model.OrderInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.other.Interface.OnValueSetClickListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.Config;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.StringConvertNumber;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.OrderPopupView;
import com.haotunet.app.goldtreasure.views.ReBuyRemindPopupView;
import com.haotunet.app.goldtreasure.views.TipPopupView;
import com.haotunet.app.goldtreasure.views.TitleView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.tongdun.android.shell.FMAgent;

public class GoldOrderActivity extends BaseActivity {
    @InjectView(R.id.title_view)
    TitleView titleView;
    @InjectView(R.id.txt_current_gold_price)
    TextView txtCurrentGoldPrice;
    @InjectView(R.id.buy_product_name)
    TextView buyProductName;
    @InjectView(R.id.buy_gold_grams)
    TextView buyGoldGrams;
    @InjectView(R.id.amount_tip)
    ImageView amountTip;
    @InjectView(R.id.pay_amount)
    TextView payAmount;
    @InjectView(R.id.txt_discount)
    TextView txtDiscount;
    @InjectView(R.id.pay_order_price)
    TextView payOrderPrice;
    @InjectView(R.id.sale_view_layout)
    LinearLayout saleViewLayout;
    @InjectView(R.id.switch_btn_discount)
    ImageView switchBtnDiscount;
    @InjectView(R.id.discount_money)
    TextView txtDiscountMoney;
    @InjectView(R.id.discount_layout)
    RelativeLayout discountLayout;
    @InjectView(R.id.switch_btn_red_packet)
    ImageView switchBtnRedPacket;
    @InjectView(R.id.red_packet_money)
    TextView redPacketMoney;
    @InjectView(R.id.red_packet_layout)
    RelativeLayout redPacketLayout;
    @InjectView(R.id.cb_protocal)
    CheckBox cbProtocal;
    @InjectView(R.id.root)
    RelativeLayout root;
    @InjectView(R.id.experience_amount)
    TextView experienceAmount;
    @InjectView(R.id.experience_gold_grams)
    TextView experienceGoldGrams;
    @InjectView(R.id.experience_gold_layout)
    LinearLayout experienceGoldLayout;
    private boolean isCouponToggle;
    private boolean isRedPacketToggle;
    private BuyConfirmModel model;
    private OrderInfo orderInfo;
    private String buyType;
    private final int MAKE_ORDER_OPERATION_SUCCESS = 4;
    private double discountMoney;
    private String productId;
    private String mGoldPrice;
    private String mOrderPrice;
    private String mGoldGrams;
    private int flag;
    private String isUseRedPacket;
    private Handler handle = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MAKE_ORDER_OPERATION_SUCCESS:
                    orderInfo = (OrderInfo) msg.obj;
                    if (orderInfo.getStatus().equals("0")) {
                        payAmount.setText(orderInfo.getOriginalPrice() + "元");
                        if (shareStore.getInt(Strs.IS_HAD_BANK_CARD, 0) == 0) {
                            ActivityUtils.gotoNewUserBuy(GoldOrderActivity.this, "1", orderInfo);
                        } else {
                            showOrderDetailView();
                        }
                    } else if (orderInfo.getStatus().equals("1")) {
                        String totalPrice = orderInfo.getCurrentOrderPrice();
                        String goldPrice = orderInfo.getCurrentGoldPrice();
                        String currentOrderQuantity = orderInfo.getCurrentOrderQuantity();
                        mGoldPrice = goldPrice;
                        mOrderPrice = totalPrice;
                        mGoldGrams = currentOrderQuantity;
                        String message = orderInfo.getMsg();
                        txtCurrentGoldPrice.setText(goldPrice);
                        payAmount.setText(orderInfo.getOriginalPrice() + "元");
                        buyGoldGrams.setText(currentOrderQuantity + "克");
                        if (model.getShowDiscountView()) {
                            payOrderPrice.setText(orderInfo.getPayment() + "元");
                        }
                        showGoldPriceChangeView(message, goldPrice);
                    }
                    break;

                default:
                    break;
            }
        }

    };
    private ShareStore shareStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gold_order);
        shareStore = new ShareStore(this);
        ButterKnife.inject(this);
        initView();
    }

    private void initView() {
        Intent intent = this.getIntent();
        buyType = intent.getStringExtra("buyType");
        flag = intent.getIntExtra("flag", 0);
        productId = intent.getStringExtra("productId");
        model = (BuyConfirmModel) intent.getSerializableExtra("buyConfirmModel");
        mGoldPrice = model.getCurrentGoldPrice();
        mOrderPrice = model.getOrderPrice();
        mGoldGrams = model.getQuantity();
        titleView.getTitletextView().setVisibility(View.VISIBLE);
        titleView.getTitletextView().setText("买金订单");
        titleView.getBackView().setVisibility(View.VISIBLE);
        titleView.getBackView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (ForgetTradePwdAct.instance != null) {
                    ForgetTradePwdAct.instance.finish();
                }
                finish();
            }
        });
        txtCurrentGoldPrice.setText(model.getCurrentGoldPrice());
        buyProductName.setText(model.getProductName());
        payAmount.setText(model.getOrderPrice() + "元");
        buyGoldGrams.setText(model.getQuantity() + "克");
        payOrderPrice = (TextView) findViewById(R.id.pay_order_price);
        isShowDiscountView();
        isShowCouponView();
        isShowRedPacketView();
        isShowExperienceGoldView();
        cbProtocal.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cbProtocal.setChecked(true);
                } else {
                    cbProtocal.setChecked(false);
                }
            }
        });
    }

    /*是否显示体验金视图*/
    private void isShowExperienceGoldView() {
        if (model.getShowExperienceGold()) {
            experienceGoldLayout.setVisibility(View.VISIBLE);
            experienceAmount.setText("-" + model.getExperienceGold() + "元");
            experienceGoldGrams.setText(model.getExperienceGoldQuality() + "克");
        }
    }

    /*是否显示特价金视图*/
    private void isShowDiscountView() {
        if (model.getShowDiscountView()) {
            saleViewLayout.setVisibility(View.VISIBLE);
            txtDiscount.setText(model.getDiscountAmount());
            payOrderPrice.setText(model.getPayment() + "元");
        }
    }

    /*是否显示优惠券视图*/
    private void isShowCouponView() {
        if (model.getShowCouponView()) {
            discountLayout.setVisibility(View.VISIBLE);
            if (flag == 0 && StringConvertNumber.parseDouble(model.getTotalCouponValue()) == 0) {
                txtDiscountMoney.setText("暂无可用优惠券");
            } else {
                txtDiscountMoney.setText("使用优惠券可抵扣" + model.getTotalCouponValue() + "元");
            }
            if (StringConvertNumber.parseDouble(model.getTotalCouponValue()) != 0) {
                switchBtnDiscount.setSelected(true);
                isCouponToggle = true;
            } else {
                isCouponToggle = false;
                switchBtnDiscount.setSelected(false);
                switchBtnDiscount.setEnabled(false);
            }
        }
    }

    //是否显示红包的视图
    private void isShowRedPacketView() {
        if (model.getShowRedPacketView()) {
            redPacketLayout.setVisibility(View.VISIBLE);
            redPacketMoney.setText(model.getRedPacketBalance() + "元");
            if (StringConvertNumber.parseDouble(model.getRedPacketBalance()) != 0) {
                switchBtnRedPacket.setSelected(true);
                isRedPacketToggle = true;
            } else {
                isRedPacketToggle = false;
                switchBtnRedPacket.setSelected(false);
                switchBtnRedPacket.setEnabled(false);
            }
        }
    }

    protected void showGoldPriceChangeView(String message, String goldPrice) {
        ReBuyRemindPopupView reBuyPopup = new ReBuyRemindPopupView(GoldOrderActivity.this, message, goldPrice, 0);
        reBuyPopup.showAtLocation(root, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
        reBuyPopup.setValueSetClickListener(new OnValueSetClickListener() {

            @Override
            public void onValueSet(String value) {
                if (value.equals("ok")) {
                    makeOrderOperation();
                } else {
                    ActivityUtils.skipToMain(GoldOrderActivity.this, "");
                }
            }
        });
    }

    protected void makeOrderOperation() {
        String blackBox = FMAgent.onEvent(GoldOrderActivity.this);
        String imei = Config.getImei(GoldOrderActivity.this);
        ActionUtil actionUtil = new ActionUtil(GoldOrderActivity.this);
        actionUtil.makeOrderOperation(mGoldGrams, mGoldPrice, mOrderPrice, model.getCouponIds(),
                discountMoney + "", isUseRedPacket, productId, buyType, imei, blackBox);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override

            public void passBack(BaseModel model) {
                if (isFinishing()) {
                    return;
                }
                OrderInfo orderModel = (OrderInfo) model;
                if (orderModel == null) {
                    UIHelper.showToast(GoldOrderActivity.this, getString(R.string.rank_fail));
                    return;
                }
                if (orderModel.getErrorMsg() != null) {
                    if (orderModel.getErrorCode().equals(Strs.EXTRUSION_SIGN_IN)) {
                        ActivityUtils.forceQuit(GoldOrderActivity.this, getString(R.string.crowding_in_tips_txt));
                    } else {
                        UIHelper.showToast(GoldOrderActivity.this, orderModel.getErrorMsg());
                    }
                } else {
                    Message msg = new Message();
                    msg.what = MAKE_ORDER_OPERATION_SUCCESS;
                    msg.obj = orderModel;
                    handle.sendMessage(msg);

                }
            }

        });
    }

    private void showOrderDetailView() {
        OrderPopupView orderPopupView = new OrderPopupView(GoldOrderActivity.this, orderInfo.getCurrentOrderPrice(),
                "1", orderInfo);
        orderPopupView.showAtLocation(root, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
        ActivityUtils.backgroundAlpha(GoldOrderActivity.this, 0.5f);
        orderPopupView.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ActivityUtils.backgroundAlpha(GoldOrderActivity.this, 1f);
            }
        });
    }

    @OnClick({R.id.amount_tip, R.id.red_packet_tip, R.id.switch_btn_discount, R.id.switch_btn_red_packet, R.id.txt_procotol, R.id.btn_pay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.amount_tip:
                new TipPopupView(GoldOrderActivity.this, null, model.getTip(), R.style.MyDialog)
                        .show();
                break;
            case R.id.red_packet_tip:
                new TipPopupView(GoldOrderActivity.this, null, model.getRedPacketTips(), R.style.MyDialog)
                        .show();
                break;
            case R.id.switch_btn_discount:
                if (isCouponToggle) {
                    switchBtnDiscount.setSelected(false);
                    isCouponToggle = false;
                } else {
                    switchBtnDiscount.setSelected(true);
                    isCouponToggle = true;
                }
                break;
            case R.id.switch_btn_red_packet:
                if (isRedPacketToggle) {
                    switchBtnRedPacket.setSelected(false);
                    isRedPacketToggle = false;
                } else {
                    switchBtnRedPacket.setSelected(true);
                    isRedPacketToggle = true;
                }
                break;
            case R.id.txt_procotol:
                ActivityUtils.gotoDynamicDetail(GoldOrderActivity.this, model.getAgreementUrl(), 8);
                break;
            case R.id.btn_pay:
                if (!cbProtocal.isChecked()) {
                    UIHelper.showToast(GoldOrderActivity.this, "请同意购买协议!");
                    return;
                }
                if (isCouponToggle) {
                    discountMoney = Double.parseDouble(model.getTotalCouponValue());
                } else {
                    discountMoney = 0;
                }
                if (isRedPacketToggle) {
                    isUseRedPacket = "1";
                } else {
                    isUseRedPacket = "0";
                }
                makeOrderOperation();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (ForgetTradePwdAct.instance != null) {
            ForgetTradePwdAct.instance.finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
